<template>
  <div>
    <a-layout>
      <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
      >
        <a-row>
          <a-col :span="8">
            <p>
              <a-form layout="inline" :model="param">
                <a-form-item>
                  <a-button type="primary" @click="add()">
                    新增
                  </a-button>
                </a-form-item>
              </a-form>
            </p>
            <a-table
              v-if="level1.length > 0"
              :columns="columns"
              :row-key="record => record.id"
              :data-source="level1"
              :pagination="false"
              :loading="loading"
              :defaultExpandAllRows="true"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                  <a-space size="small">
                    <a-button type="primary" @click="edit(record)">
                      编辑
                    </a-button>
                    <a-popconfirm
                      title="删除后不可以恢复，确认删除?"
                      ok-text="是"
                      cancel-text="否"
                      @confirm="handleDelete(record.id)"
                    >
                      <a-button danger>
                        删除
                      </a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-col>
          <a-col :span="16">
            <p>
              <a-form layout="inline">
                <a-form-item>
                  <a-button type="primary" @click="handleSave()">
                    保存
                  </a-button>
                </a-form-item>
              </a-form>
            </p>
            <a-form :model="doc" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-form-item>
                <a-input v-model:value="doc.name" placeholder="名称" />
              </a-form-item>
              <a-form-item>
                <a-tree-select
                  v-model:value="doc.parent"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择父文档"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="treeSelectData"
                  tree-node-filter-prop="label"
                  :replaceFields="{ children: 'children', label: 'name', key: 'id', value: 'id' }"
                >
                </a-tree-select>
              </a-form-item>
              <a-form-item>
                <a-tree-select
        v-model:value="doc.parent"
        show-search
        style="width: 100%"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        placeholder="请选择树文档"
        allow-clear
        tree-default-expand-all
        :tree-data="level1"
        tree-node-filter-prop="label"
        :replaceFields ="{children:'children', label:'name', key:'id', value: 'id' }"
      >
      </a-tree-select>
    </a-form-item>
              <a-form-item>
                <a-input v-model:value="doc.sort" placeholder="顺序" />
              </a-form-item>
              <a-form-item>
                <div style="border: 1px solid #ccc">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 300px; overflow-y: auto;"
                    v-model:content="doc.content"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                  />
                </div>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ref, onMounted, shallowRef, watch } from 'vue';
import { useRoute } from 'vue-router';
import { Tool } from "@/utils/tool.ts";
import { message } from 'ant-design-vue';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const route = useRoute();
const docs = ref();
const param = ref({});
param.value = {};
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});
const loading = ref(false);
const columns = [
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: 'Action',
    key: 'action',
    dataIndex: 'action'
  }
];
const level1 = ref([]);
const doc = ref({
  id: null,
  name: "",
  parent: 0,
  ebookId: route.query.ebookId || 0,
  sort: 0,
  content: ""
});
const modalVisible = ref(false);
const modalLoading = ref(false);
const treeSelectData = ref([]);
const editorRef = shallowRef();
const editorInitialized = ref(false);
const contentLoaded = ref(false);
const toolbarConfig = {
  // 配置工具栏按钮
  menus: ['bold', 'italic', 'underline', 'fontSize', 'fontFamily', 'paragraph', 'lineHeight', 'link', 'image']
};
const editorConfig = {};
const mode = 'default';

const handleQuery = () => {
  loading.value = true;
  axios.get("http://localhost:8080/obwiki/doc/all").then((resp) => {
    loading.value = false;
    const data = resp.data;
    if (data.success) {
      level1.value = [];
      level1.value = Tool.array2Tree(data.content, 0);
      console.log("树形结构：", level1.value);
    }
  });
};

const edit = (record: any) => {
  doc.value = Tool.copy(record);
  modalVisible.value = true;
  contentLoaded.value = false;
  
  // 确保编辑器初始化后再加载内容
  if (editorInitialized.value) {
    handleQueryContent();
  }
  
  treeSelectData.value = Tool.copy(level1.value);
  setDisable(treeSelectData.value, record.id);
  treeSelectData.value.unshift({ id: 0, name: '无' });
};

const add = () => {
  modalVisible.value = true;
  doc.value = {
    id: null,
    name: "",
    parent: 0,
    ebookId: route.query.ebookId || 0,
    sort: 0,
    content: ""
  };
  contentLoaded.value = false;
  
  // 清空编辑器
  if (editorInitialized.value) {
    editorRef.value.setHtml('');
  }
  
  treeSelectData.value = Tool.copy(level1.value);
  treeSelectData.value.unshift({ id: 0, name: '无' });
};

const ids: Array<string> = [];
const deleteNames: Array<string> = [];
const getDeleteIds = (treeSelectData: any, id: any) => {
  for (let i = 0; i < treeSelectData.length; i++) {
    const node = treeSelectData[i];
    if (node.id === id) {
      ids.push(id);
      deleteNames.push(node.name);
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        for (let j = 0; j < children.length; j++) {
          getDeleteIds(children, children[j].id);
        }
      }
    } else {
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        getDeleteIds(children, id);
      }
    }
  }
};

const handleDelete = (id: number) => {
  ids.length = 0;
  deleteNames.length = 0;
  getDeleteIds(level1.value, id);
  axios.get(`http://localhost:8080/obwiki/doc/remove?ids=${ids.join(",")}`).then((response) => {
    const data = response.data;
    if (data.success) {
      message.success(`已删除文档: ${deleteNames.join('、')}`);
      handleQuery();
    } else {
      message.error(data.message);
    }
  });
};

const setDisable = (treeSelectData: any, id: any) => {
  for (let i = 0; i < treeSelectData.length; i++) {
    const node = treeSelectData[i];
    if (node.id === id) {
      node.disabled = true;
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        for (let j = 0; j < children.length; j++) {
          setDisable(children, children[j].id);
        }
      }
    } else {
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        setDisable(children, id);
      }
    }
  }
};

const handleSave = () => {
  modalLoading.value = true;
  
  // 确保编辑器已初始化
  if (!editorRef.value) {
    message.error('编辑器未就绪');
    modalLoading.value = false;
    return;
  }
  
  // 更新文档内容
  doc.value.content = editorRef.value.getHtml();
  
  axios.post("http://localhost:8080/obwiki/doc/save", doc.value).then((resp) => {
    const data = resp.data;
    if (data.success) {
      modalLoading.value = false;
      message.success("保存成功！");
      modalVisible.value = false;
      handleQuery();
    } else {
      modalLoading.value = false;
      message.error(data.message || '保存失败，请重试');
    }
  });
};

const handleCreated = (editor) => {
  console.log('编辑器初始化完成');
  editorRef.value = editor;
  editorInitialized.value = true;
  
  // 编辑器初始化后，如果有文档ID且内容未加载，加载内容
  if (doc.value.id && !contentLoaded.value) {
    handleQueryContent();
  }
};

const handleQueryContent = () => {
  if (!editorInitialized.value || !doc.value.id) return;
  
  contentLoaded.value = true;
  axios.get(`http://localhost:8080/obwiki/content/findContent/${doc.value.id}`).then((response) => {
    const data = response.data;
    if (data.success && editorRef.value) {
      editorRef.value.setHtml(data.content || '');
    } else {
      message.error(data.message || '获取内容失败');
    }
  });
};

// 监听doc.id的变化，当ID变化时重新加载内容
watch(() => doc.value.id, (newId) => {
  if (newId && editorInitialized.value) {
    handleQueryContent();
  }
});

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
  .wangeditor {
    min-height: 300px;
  }
</style>